use std::{
    env,
    fs::{self, DirEntry},
    process::{self, Stdio},
};

fn main() {
    let nvm_home = env::var("NVM_HOME");

    match nvm_home {
        Ok(nvm_path) => {
            let dir = fs::read_dir(nvm_path).expect("读取文件夹失败!");
            let node_list: Vec<DirEntry> = dir
                .into_iter()
                .filter_map(|item| match item {
                    Ok(i) if i.file_name().to_string_lossy().starts_with("v") => Some(i),
                    Ok(_) => None,
                    Err(_) => None,
                })
                .collect();

            let args: Vec<String> = env::args().collect();

            let node_one = node_list.iter().find(|item| {
                item.file_name()
                    .to_string_lossy()
                    .starts_with(&format!("v{}", args[1]))
            });
            if let Some(one) = node_one {
                let node_path = one.path().to_path_buf();
                let mut new_path = env::var("PATH").unwrap_or_else(|_| String::new());
                new_path = format!("{};{}", node_path.display(), new_path);

                let output = process::Command::new("cmd")
                    .arg("/c")
                    .env("PATH", new_path)
                    .arg(node_path.join("npm.cmd"))
                    .args(&args[2..])
                    .stdin(Stdio::inherit())
                    .stdout(Stdio::inherit())
                    .stderr(Stdio::inherit())
                    .status()
                    .unwrap();
                println!("Command exited with status: {:?}", output);
            }
        }
        Err(_) => {
            println!("请安装nvm")
        }
    }
}
